import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created with IntelliJ IDEA.
 * Description: TCP协议实现服务端代码
 * User: 87111
 * Date: 2025-11-18
 * Time: 21:11
 */
public class TcpEchoServer {
    private ServerSocket socket = null;
    //构造对象，并绑定端口号
    public TcpEchoServer(int port) throws IOException {
        //设置服务器端口号
        socket = new ServerSocket(port);
    }

    public void start() throws IOException {
        //启动服务器
        System.out.println("启动服务器");

        //创建线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        while(true) {
            //TCP需要先处理客户端发来的连接
            //如果没有连接，就会阻塞等待客户端的连接
            //如果连接成功，就通过clientSocket来和客户端进行通信
            Socket clientSocket = socket.accept();

            //有可能多个客户端访问当前服务器
            //方法一：此时可以每次跟一个客户端建立连接后，创建一个线程处理客户端的请求
//            Thread t = new Thread(() -> {
//                processConnection(clientSocket);
//            });
//            t.start();

            //创建线程和销毁线程也会消耗资源。
            // 方法二：使用线程池的方法来解决多个客户端访问服务器的情况
            executorService.submit(() -> {
                processConnection(clientSocket);
            });
        }

    }

    //处理一个客户端的连接
    //有可能会有多个客户端进行请求和响应
    public void processConnection(Socket clientSocket) {
        System.out.println("客户端上线了");
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()) {
            //针对输入流和输出流又套了一层
            //接收请求
            Scanner sc = new Scanner(inputStream);
            //发送响应
            PrintWriter writer = new PrintWriter(outputStream);

            while(true) {
                //1. 读取请求，并解析
                if(!sc.hasNext()) {
                    System.out.println("没有请求");
                }
                String request = sc.next();
                //2.根据请求，计算响应
                String response = process(request);
                //3.将响应发送给客户端
                writer.println(response);
                //刷新缓冲区
                writer.flush();

                //打印日志
                System.out.printf("[%s,%d] request: %s response: %s\n",clientSocket.getInetAddress(),clientSocket.getPort(),
                        request,response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                //这里如果完成通信后，要及时关闭socket建立的连接
                clientSocket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(9090);
        server.start();
    }

}
